<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检索" prop="search">
        <el-input v-model="queryParams.search" placeholder="请输入检索信息" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类">
          <el-option v-for="item in categoryList" :label="item.frontName" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布日期" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择发布日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="opStatus">
        <el-select v-model="queryParams.opStatus" placeholder="选择状态">
          <el-option label="正常" value="0"></el-option>
          <el-option label="下架" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['manage:news:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:news:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:news:remove']">删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="newsTitle" />
      <el-table-column label="简介" align="center" prop="newsIntro" />
      <el-table-column label="封面" prop="newsPhoto" width="110" height="50">
        <template slot-scope="scope">
          <el-image :src="scope.row.newsPhoto" fit="cover" style=" width:20; height:20;">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" align="center" prop="newsCount">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.newsCount != null">
            {{ scope.row.newsCount }}
          </el-tag>
          <el-tag effect="dark">
            暂无
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" align="center" prop="categoryName" />
      <el-table-column label="状态" align="center" prop="opStatus">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.opStatus" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="发布人" align="center" prop="newsCreate" width="180">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger">
            {{ scope.row.newsCreate }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:news:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:news:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改资讯对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="newsTitle">
          <el-input v-model="form.newsTitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="简介" prop="newsIntro">
          <el-input type="textarea" :rows="2" v-model="form.newsIntro" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="封面" prop="newsPhoto">
          <el-upload class="upload-demo" v-model="form.newsPhoto" action="/dev-api/common/upload"
            :on-success="handleSuccess" :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">上传封面</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="发布人" prop="newsCreate" v-if="form.newsId != null">
          <el-input :disabled="true" v-model="form.newsCreate" placeholder="请输入发布人" />
        </el-form-item>

        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option v-for="item in categoryList" :label="item.frontName" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.newsRemark" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { changeUserStatus, listNews, getNews, delNews, addNews, updateNews } from "@/api/manage/news";
import { getListCategortName } from "@/api/manage/category"
export default {
  name: "News",
  data () {
    return {
      fileList: [],
      categoryList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资讯表格数据
      newsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        search: null,
        categoryId: null,
        opStatus: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        newsTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        newsIntro: [
          { required: true, message: "简介不能为空", trigger: "blur" }
        ],
        newsRemark: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "发布时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created () {
    this.getList();
  },
  methods: {
    // 上传成功 回调函数
    handleSuccess (response, file, fileList) {
      if (response.code == '500') {
        this.$message.error(response.msg)
        return;
      }
      console.log(response);
      var data = {
        name: response.newFileName,
        url: response.url
      }
      this.fileList.push(data)
      this.form.newsPhoto = response.url
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.opStatus === "0" ? "上架" : "下架";
      this.$modal.confirm('确认要"' + text + '""' + row.newsTitle + '"内容吗？').then(function () {
        return changeUserStatus(row.newsId, row.opStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.opStatus = row.opStatus === "0" ? "1" : "0";
      });
    },
    // 查询所有分类名
    getCategortName () {
      getListCategortName().then(res => {
        this.categoryList = res.data;
      })
    },
    /** 查询资讯列表 */
    getList () {
      this.loading = true;
      this.getCategortName();
      listNews(this.queryParams).then(response => {
        this.newsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.newsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加资讯";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const newsId = row.newsId || this.ids
      getNews(newsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资讯";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addNews(this.form).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const newsIds = row.newsId || this.ids;
      this.$modal.confirm('是否确认删除资讯编号为"' + newsIds + '"的数据项？').then(function () {
        return delNews(newsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('manage/news/export', {
        ...this.queryParams
      }, `news_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
